String.format = function(str) {
    var args = arguments, re = new RegExp("%([1-" + args.length + "])", "g");
    return String(str).replace(
    re,
    function($1, $2) {
        return args[$2];
    }
    );
};

String.formatmodel = function(str,model){
	for(var k in model){
		var re = new RegExp("{"+k+"}","g");
		str = str.replace(re,model[k]);
	}
	return str;
}

var Util = {};

Util.CONFIG = {
	SQBrdColor: "#072246",
	SQBgColor: "#6bb0c9",
	SQOpacity: 15,
	SQScrollStep: 6,
	
	TextBoxDefaultColor: "#808080",
    TextBoxActiveColor:"#000"
}

Util.CACHE = {};

Util.AddBookmark = function(title,url) {
	if (window.sidebar) { 
		window.sidebar.addPanel(title, url,""); 
	} else if( document.all ) {
		window.external.AddFavorite( url, title);
	} else {
		alert("您的浏览器不支持自动加入收藏夹，请使用浏览器菜单手动加入");
	}
}

Util.SetHome = function(ele){
	if( document.all ){
		ele.style.behavior='url(#default#homepage)'; 
		ele.setHomePage(window.location.href);
	}
	else{
		//var c = chrome;
		//chrome.send('setHomePage', [window.location.href, "1"]);
		alert("您的浏览器不支持自动设置主页，请使用浏览器菜单手动设置");
	}
}

function getClipboardData(){
	window.document.ff_clipboard_swf.SetVariable('str', Util.CACHE.CLIPBOARD_TEXT);
}

function hideMenu(){
	Util.CACHE.CopyBox && Util.CACHE.CopyBox.hide();
}

/*
*
* 复制
*/
Util.Copy = function(pStr,hasReturn, isdo){
	var result = false;
    //IE
    if(window.clipboardData)
    {
        window.clipboardData.clearData();
        result = window.clipboardData.setData("Text", pStr);
    }
    //FireFox
    else
    {
		if(top.window && !isdo){
			top.window.Util.Copy(pStr,hasReturn, true);
			return;
		}
		Util.CACHE.CLIPBOARD_TEXT = pStr;
		if(!Util.CACHE.CopyBox){
			Util.CACHE.CopyBox = $('<div id="ff_clipborad_swf_box" style="position:absolute;width:220px;padding:8px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;background:#CBCBCB;background:rgba(0, 0, 0, 0.2);overflow:hidden; z-index:99999999999;">'+
				'<div style="padding:6px 10px 10px;background:#FFF;overflow:hidden;">'+
					'<h3 style="height:30px;margin:0;padding:0;overflow:hidden;font-size:14px;"><span style="float:left;line-height:30px;">提示信息</span><a href="javascript:;" style="float:right;width:18px;height:18px;margin-top:5px;line-height:18px;text-align:center;overflow:hidden;font-size:12px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;color:#FFF;background:#A4A4A4;" onclick="'+"$('#ff_clipborad_swf_box').hide();"+'">X</a></h3>'+
					'<div style="position:relative;height:40px;overflow:hidden;line-height:35px;text-align:center;text-decoration:underline;" id="js_ff_copy_box_con">点此复制到剪切板</div>'+
				'</div>'+
			'</div>');
			//创建Flash按钮
			$(document.body).append(Util.CACHE.CopyBox);
		}
		if(document.getElementById('ff_clipboard_swf')){
			$("#ff_clipboard_swf").empty().remove();
		}
		var html = [];
		html.push('<object type="application/x-shockwave-flash" data="'+PAGE_PATHS["MY"]+'/statics/web/js/clipboard.swf" width="200" height="40" style="position:relative;top:-35px;" id="ff_clipboard_swf">');
		html.push('<param name="quality" value="high" />');
		html.push('<param name="allowScriptAccess" value="sameDomain" />');
		html.push('<param name="allowFullScreen" value="true" />');
		html.push('<param name="wmode" value="transparent" />');
		html.push('</object>');
		$("#js_ff_copy_box_con").append(html.join(""));
		Util.Layer.Center(Util.CACHE.CopyBox);
		Util.CACHE.CopyBox.show();
		return;
    }
	if(hasReturn){
    	return result;
	}
	else{
		if(result){
			alert("内容已复制至剪贴板!");
		}
		else{
			alert("复制失败! 您使用的浏览器不支持复制功能.");
		}
	}
}

/*
* 文件
*/
Util.File = {
    /**
    * 显示文件大小
    *
    *
    */
    ShowSize:function(bytes, fix){
        bytes = parseInt(Number(bytes));
        var unit = new Array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB',
        'DB', 'NB');
        var extension = unit[0];
        var max = unit.length;
        for (var i = 1; ((i < max) && (bytes >= 1024)); i++) {
            bytes = bytes / 1024;
            extension = unit[i];
        }
		
        return Number(bytes).toFixed((fix == undefined)?2:fix) + extension;
    },
	GetInputFilePath: function (ele){  
		if(ele){  
			if (window.navigator.userAgent.indexOf("MSIE")>=1){  
				ele.select();  
				return document.selection.createRange().text;
			}
			else if(window.navigator.userAgent.indexOf("Firefox")>=1){  
				if(ele.files){  
					return ele.files.item(0).getAsDataURL();  
				}  
				return ele.value;  
			}  
			return ele.value;  
		}  
	},
	FileNameCut: function(file_name){
        var lL = file_name.lastIndexOf(".");
        var pey = file_name.substring(lL);
        var name = file_name.substring(0,lL);
        var flong = Util.Validate.mb_strlen(file_name);
        var plong = Util.Validate.mb_strlen(pey);
        if(flong > 451){
            if(plong > 451){
                pey = pey.substring(0,400);
                if(Util.Validate.mb_strlen(name+pey) > 451){
                    name = name.substring(0,49);
                }
            }
            else{
                var lesslong = flong - plong;
                name = name.substring(0,lesslong - 1);
            }
        }
        return name + pey;
    }
}

Util.Text = {
	Cut: function(str,count){
		if(str.length > count){
			return str.substring(0,count/2) + "..." + str.substring(str.length - (count/2),str.length);
		}
		return str;
	},
    GetCount: function(str){
		var len = str.length;
		var reLen = 0;
		for (var i = 0; i < len; i++) { 
			if (/^[\u4e00-\u9fa5]{0,}$/.test(str.substring(i, i+1))) {
				// 全角    
				reLen += 2;
			}
            else {
				if(reLen == 0){
					reLen++;
				}
				reLen++;
			}
		}
		return reLen; 	
	},
	htmlspecialchars: function(string, quote_style, charset, double_encode) {
		var optTemp = 0,
			i = 0,
			noquotes = false;
		if (typeof quote_style === 'undefined' || quote_style === null) {
			quote_style = 2;
		}
		string = string.toString();
		if (double_encode !== false) { // Put this first to avoid double-encoding
			string = string.replace(/&/g, '&amp;');
		}
		string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
	
		var OPTS = {
			'ENT_NOQUOTES': 0,
			'ENT_HTML_QUOTE_SINGLE': 1,
			'ENT_HTML_QUOTE_DOUBLE': 2,
			'ENT_COMPAT': 2,
			'ENT_QUOTES': 3,
			'ENT_IGNORE': 4
		};
		if (quote_style === 0) {
			noquotes = true;
		}
		if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
			quote_style = [].concat(quote_style);
			for (i = 0; i < quote_style.length; i++) {
				// Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
				if (OPTS[quote_style[i]] === 0) {
					noquotes = true;
				}
				else if (OPTS[quote_style[i]]) {
					optTemp = optTemp | OPTS[quote_style[i]];
				}
			}
			quote_style = optTemp;
		}
		if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
			string = string.replace(/'/g, '&#039;');
		}
		if (!noquotes) {
			string = string.replace(/"/g, '&quot;');
		}
	
		return string;
	}
}

Util.Date = {
	GetTimeText:function(num){
		var arr = [3600,60];
		var result = "";
		for(var i = 0,len = arr.length; i < len; i++){
			var item = arr[i];
			if(num >= item){
				var s = (num / item).toFixed(0);
				result += Util.Date._getDoubleText(s) + ":";
				num = num % item;
			}
			else{
				result += "00:";
			}
		}
		result += Util.Date._getDoubleText(num);
		return result;
	},
	GetIMText: function(h,m,s){
		var txt = [];
		if(h < 10){
			txt.push("0" + h);
		}
		else{
			txt.push(h);
		}
		if(m < 10){
			txt.push("0" + m);
		}
		else{
			txt.push(m);
		}
		if(s < 10){
			txt.push("0" + s);
		}
		else{
			txt.push(s);
		}
		return txt.join(":");
	},
	_getDoubleText: function(num){
		if(num.toString().length > 1){
			return num;
		}
		else{
			return "0" + num.toString();
		}
	}
}

/*
* Cookie控制
*/
Util.Cookie = {
    get:function(name){
        var cookieValue = "";
        var search = name + "=";
        if (document.cookie.length > 0) {
            offset = document.cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = document.cookie.indexOf(";", offset);
                if (end == -1)
                end = document.cookie.length;
                cookieValue = unescape(document.cookie.substring(offset, end));
            }
        }
        return cookieValue;
    },
    set:function(name, value, hours){
        var expire = "";
        if (hours != null) {
            expire = new Date((new Date()).getTime() + hours * 3600000);
            expire = "; expires=" + expire.toGMTString();
        }
        document.cookie = name + "=" + escape(value) + expire +";path=/";
    }
}

Util.TextBox = {
    BindDefaultText: function(ele,text){
        ele.value = text;
        ele.style.color = Util.CONFIG.TextBoxDefaultColor;
        ele.onblur = function(){
            if(ele.value == ""){
                ele.value = text;
                ele.style.color = Util.CONFIG.TextBoxDefaultColor;
            }
            else{
                ele.style.color = Util.CONFIG.TextBoxActiveColor;
            }
        };
        ele.onfocus = function(){
            ele.style.color = Util.CONFIG.TextBoxActiveColor;
            if(ele.value == text){
                ele.value = "";
            }
        };
        ele.GetValue = function(){
            if(ele.value == text){
                return "";
            }
            return ele.value;
        };
		ele.Clear = function(){
			ele.value = "";
			ele.onblur();
		};
        return ele;
    }
}

Util.DropDown =  (function(){
	var _timeout = 300, _hide_status = "hide_status";
	return {
		Bind: function(st){
			st.Title.bind("click",{setting: st},function(e){ 
				var setting = e.data.setting;
                if(setting.overtimer) window.clearTimeout(setting.overtimer);
				setting.Title.attr(_hide_status,"0");
				setting.Content.show();
				if(setting.ShowHandler){
					setting.ShowHandler();
				}
			}).bind("mouseover",{setting: st},function(e){
				var setting = e.data.setting;
                if(setting.overtimer) window.clearTimeout(setting.overtimer);
				if(setting.IsOverShow){
                    setting.overtimer = window.setTimeout(function(){
                        setting.Title.attr(_hide_status,"0");
                        setting.Content.show();
                        if(setting.ShowHandler){
                            setting.ShowHandler();
                        }
                    },_timeout);
				}
				if(setting.Title.attr(_hide_status) == "1"){
					setting.Title.attr(_hide_status,"0");
				}
			}).bind("mouseleave",{setting: st},function(e){
				var setting = e.data.setting;
				if(setting.timer){
					window.clearTimeout(setting.timer);
				}
                if(setting.overtimer) window.clearTimeout(setting.overtimer);
				if(setting.Title.attr(_hide_status) == "0"){
					setting.Title.attr(_hide_status,"1");
					setting.timer = window.setTimeout(function(){
						if(setting.Title.attr(_hide_status) == "1"){
							if(setting.HideHandler){
								setting.HideHandler();
							}
							setting.Content.hide();
						}
						window.clearTimeout(setting.timer);
						delete setting.timer;
					},_timeout);
				}
			})
			st.Content.bind("mouseover",{setting: st},function(e){
				var setting = e.data.setting;
				if(setting.Title.attr(_hide_status) == "1"){
					setting.Title.attr(_hide_status,"0");
				}
			}).bind("mouseleave",{setting: st},function(e){
				if($.browser.msie){
					event.cancelBubble=true;
				}else{
					e.stopPropagation();
					e.preventDefault();
				}	//停止冒泡
				var setting = e.data.setting;
				if(setting.timer){
					window.clearTimeout(setting.timer);
				}
                if(setting.overtimer) window.clearTimeout(setting.overtimer);
				setting.Title.attr(_hide_status,"1");
				setting.timer = window.setTimeout(function(){
					if(setting.Title.attr(_hide_status) == "1"){
						if(setting.HideHandler){
							setting.HideHandler();
						}
						setting.Content.hide();
					}
					window.clearTimeout(setting.timer);
					delete setting.timer;
				},_timeout);
			}).hide();
		}
	}
})();

Util.Load = {
	_download: function(type, code, complete, isremove){
		$(code).bind("load",function(){
			isremove && $(code).remove();
			if(complete) complete();
		})
		if(type != "css"){
			code.onreadystatechange = (function(){
				if(code.readyState == "complete" || code.readyState == "loaded"){
					//document.body.removeChild(code);
					isremove && $(code).remove();
					if(complete) complete();
				}
			});
		}
		document.body.appendChild(code);
	},
	JS: function(url,complete, isremove){
		if(isremove == undefined){
			isremove = true;
		}
		var code = document.createElement("script");
		code.src = url;
		Util.Load._download("script", code, complete, isremove);
	},
	Css: function(url, complete){
		var code = document.createElement("link");
		code.href = url;
		code.rel = "stylesheet";
		code.type = "text/css";
		Util.Load._download("css", code, complete);
		return;
	}
}

/**
* 验证
*/
Util.Validate = {
    mb_strlen: function(str){
        var offset = 0;
        for(var i=0; i<str.length; i++){
            var string = str.substr(i,1);
            if(escape(string).substr(0,2)=="%u"){
                offset +=3;
            }
            else{
                offset +=1;
            }
        }
        return offset;
    },
    FileName: function(file_name) {
        if (file_name.length < 1) {
            alert('文件名不能少于1个字符！');
            return false;
        }
        var regular = /^[^\\/:*?<>\s\"\']{1,}$/;
        if (!regular.test(file_name)) {
            alert("文件名不能包含下列任意字符之一\n\ / :. * ?\" < > |");
            return false;
        }
        return true;
    },
    Desc: function(description) {
        if (description.length > 11500) {
            alert('描述字符长度不能超过11500字节');
            return false;
        }
        return true;
    },
    CategoryName: function(category_name) {
        category_name = category_name.replace(' ', '');
        if (category_name.length < 1) {
            return '目录名称不能为空。';
        }
        if (category_name.length > 50) {
            return '目录名称不能超过50个字。';
        }
        var regular = /^[^\\/:*?<>\|\\\\\"]*$/;
        if (!regular.test(category_name)) {
            return "目录名称不能包含下列任意字符之一\n\ \\ / : * ? \"  < > |";
        }
        return true;
    },
    Email: function(email) {
        var regular = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/;
        if (!regular.test(email)) {
            return false;
        } else {
            return true;
        }
    }
};

/*
	Tab切换
*/
Util.TabManager = function(pList,pActiveStyle,pDisableStyle){
	var _self = this;
	var _obj = {
		List: pList,
		ActiveStyle: pActiveStyle,
		DisableStyle: pDisableStyle
	};
	var _ChangeHandler;
	var time ;
	var _autoTimer;
	this._autoTimeOut = 3000;
	this.Animate = false
	var overObj;
	var activeIndex;
	var _autostate = false;
	function display(){
		for(var j = 0; j < _obj.List.length; j++){
			var ele = _obj.List[j].Tab;
			ele.removeClass(_obj.ActiveStyle);
			ele.addClass(_obj.DisableStyle);
			_obj.List[j].Content.hide();
		}

		overObj.Tab.addClass(_obj.ActiveStyle);
		if(_self.Animate){
			overObj.Content.fadeIn();
		}
		else{
			overObj.Content.show();
		}
		if(_ChangeHandler){
			_ChangeHandler(overObj);
		}
	}

	function autoDisplay(){
		activeIndex++;
		if(activeIndex >= _obj.List.length){
			activeIndex = 0;
		}
		overObj = _obj.List[activeIndex];
		display();
	}

	var init = function(){
		for(var i = 0; i < _obj.List.length; i++){
			var item = _obj.List[i];
			item.Tab.bind("mouseover",{obj:item,index:i},function(e){
				overObj = e.data.obj;
				activeIndex = e.data.index;
				time = window.setTimeout(display,300);
				_self.SetAuto(_autostate);
			}).bind("click",{obj:item,index:i},function(e){
				overObj = e.data.obj;
				activeIndex = e.data.index;
				if(time != undefined){
					window.clearTimeout(time);
				}
				display();
				this.blur();
				_self.SetAuto(_autostate);
			}).bind("mouseout",function(){
				if(time != undefined){
					window.clearTimeout(time);
				}
			});
		}

	}
	
	
	this.Stop = function(){
		if(_autoTimer){
			window.clearInterval(_autoTimer);
		}
	}
	
	this.Start = function(){
		_self.SetAuto(_autostate);
	}
	
	this.SetAuto = function(v){
		if(_autoTimer){
			window.clearInterval(_autoTimer);
		}
		if(v){
			_autoTimer = window.setInterval(autoDisplay,_self._autoTimeOut);
		}
		_autostate = v;
	}
	this.SetChangeHandler = function(pHandler){
		_ChangeHandler = pHandler;
	},
	this.Select = function(key){
		activeIndex = key;
		overObj = _obj.List[key];
		display();
	}
	init();
}


Util.ChatEditBox = {
	lastRange:null ,
	lastBookmark:null,
	Newline: function(isnotadd){
		if ($.browser.msie) {
			var i = document.selection.createRange();
			!isnotadd || i.pasteHTML("<br />");
			i.collapse(false);
			i.select();
		} else {
			if ($.browser.webkit) {
				var k = window.getSelection();
				var i = k.getRangeAt(0);
				var j = i.createContextualFragment("<br/>&nbsp;");
				var l = j.lastChild;
				i.insertNode(j);
				i.setEndAfter(l);
				i.setStartAfter(l);
				k = window.getSelection();
				k.removeAllRanges();
				k.addRange(i);
				var m = l.previousSibling;
				document.execCommand("Delete", false, null);
				m.scrollIntoView();
			} else {
				if ($.browser.opera) {} else {
					if ($.browser.mozilla) {
						var i = window.getSelection().getRangeAt(0);
						var j = i.createContextualFragment("<br>");
						var l = j.lastChild;
						i.insertNode(j);
						i.setEndAfter(l);
						i.setStartAfter(l);
						var k = window.getSelection();
						k.removeAllRanges();
						k.addRange(i);
					} else {}
				}
			}
		}
	},
	clear: function(edit) {
		if ($.browser.msie) {
			edit.innerHTML = "";
		} else {
			if ($.browser.webkit) {
				var j = window.getSelection();
				var i = j.getRangeAt(0);
				edit.innerHTML = "<br/>";
				var j = getSelection();
				j.removeAllRanges();
				j.addRange(i);
			} else {
				edit.innerHTML = "<br/>";
			}
		}
		this.lastBookmark = null;
		this.lastRange = null;
		this.Focus(edit, true);
	},
	getSelection: function() {
		return (document.selection) ? document.selection: window.getSelection();
	},
	getRange: function() {
		var k = this.getSelection();
		if (!k) {
			return null;
		}
		try {
			var i = k.createRange ? k.createRange() : k.getRangeAt(0);
			var l = null;
			var j = this.editArea;
			if (i.commonAncestorContainer) {
				l = i.commonAncestorContainer;
			} else {
				if (i.parentElement) {
					l = i.parentElement();
				}
			}
			if (l && (l == j || l.parentNode == j || l.parentNode.parentNode == j)) {
				return i;
			} else {
				return null;
			}
		} catch(m) {
			return null;
		}
	},
	simpleSaveRange: function() {
		try{
		var i = this.getSelection();
		this.lastRange = i.createRange ? i.createRange() : i.getRangeAt(0);
		if (this.lastRange.getBookmark) {
			this.lastBookmark = this.lastRange.getBookmark();
		}
		}catch(e){}
	},
	saveRange: function() {
		var i = this.getRange();
		if (!i) {
			return;
		}
		this.lastRange = i;
	},
	ClearHtml: function(i) {
		var j = false;
		var k = i.replace(/<!-{2,}[\s\S]*?-{2,}>/g, "");
		k = k.replace(/<([^>]+).*?>/ig,
		function(n, m) {
			var l = m.split(" ")[0].toLowerCase();
			switch (l) {
			case "/p":
				return "<br>";
			case "br":
				if (j) {
					j = false;
					return "";
				}
				return n;
			case "img":
				j = true;
				if (n.toLowerCase().indexOf("mark") > 0) {
					return n;
				} else {
					return "";
				}
			default:
				return "";
			}
		});
		k = k.replace(/\n/g, "");
		return k;
	},
	Focus: function(edit, k) {
		if (!k && !!this.getRange()) {
			return;
		}
		edit.focus();
		if (this.lastRange && !$.browser.msie) {
			var j = window.getSelection();
			j.removeAllRanges();
			j.addRange(this.lastRange);
		}
		if ($.browser.opera) {
			edit.focus();
		}
		if (this.lastBookmark) {
			var i = document.selection.createRange();
			i.moveToBookmark(this.lastBookmark);
			i.collapse(false);
			i.select();
			this.lastBookmark = null;
		}
	},
	InsertHtml: function(o,  l, k) {
		//var o = this.editArea;
		var q = {editArea: o};
		if (document.all) {
			var m = this.getRange();
			if(this.lastRange){
				m = this.lastRange;
			}
			if (m) {
				m.collapse(false);
				m.select();
				m.pasteHTML(l);
				m.select();
			} else {
				o.innerHTML += l;
				var i = o.lastChild;
			}
			var i = o.lastChild;
			if (k) {
				while (i && i.nodeName.toLowerCase() == "br") {
					var j = i;
					i = i.previousSibling;
					o.removeChild(j);
				}
			}
		} else {
			if (window.getSelection) {
				var m = this.getRange();
				if (this.lastRange) {
					m = this.lastRange;
				}
				if (!m) {
					o.innerHTML += l;
					var i = o.lastChild;
				} else {
					m.collapse(false);
					var n = m.createContextualFragment(l);
					var i = n.lastChild;
					if (k) {
						while (i && i.nodeName.toLowerCase() == "br" && i.previousSibling && i.previousSibling.nodeName.toLowerCase() == "br") {
							var j = i;
							i = i.previousSibling;
							n.removeChild(j);
						}
					}
					m.insertNode(n);
					if (i) {
						m.setEndAfter(i);
						m.setStartAfter(i);
					}
					var p = getSelection();
					p.removeAllRanges();
					p.addRange(m);
				}
			}
		}
		setTimeout(function() {
			q.editArea.scrollTop = q.editArea.scrollHeight;
			q.editArea.scrollLeft = q.editArea.scrollWidth;
		},
		200);
	}
}

Util.Url = {
	ReplaceQueryVar:function(skey, svalue){
		var href = location.href;
		if(location.hash){
			href = href.replace(location.hash,'');
		}
		var urls = href.split('?');
		var kws  = urls[1].split('&');
		var kw = newurl = '';
		var ischange = 0;
		for(i=0; i < kws.length; i++ ){
			kw = $.trim(kws[i]);
			if( kw=='' ){
				continue;
			}
			else{
				kwss = kws[i].split('=');
				if( kwss.length < 2 ) continue;
				if( kwss[0]==skey ){
					if( kwss[1] != svalue ){
						kwss[1] = svalue;
						ischange = 2;
					} else {
						ischange = 1;
					}
				}
				if( kwss[1] != '' ){
					newurl += (newurl=='' ? kwss[0] + '=' + kwss[1] : '&' + kwss[0] + '=' + kwss[1]);
				}
			}
		}
		if( ischange==0 ){
			newurl += '&'+ skey + '=' + svalue;
		}
		var url;
		if( ischange != 1){
			url = urls[0]+'?'+newurl;
		} else {
			url = location.href;
		}
		window.location.href = url;
	}
}

Util.Log = (function(){
	var _cache = {};
	return {
		write: function(msg){
			if(!_cache.box){
				_cache.box = $("<div style='position:absolute;top:0;left:0;background:#fff;'></div>");
				$(document.body).append(_cache.box);
			}
			_cache.box.html(msg);
		}
	}
})()

/*
	公共函数
*/
Util.Mouse = (function(){
    var _cache = {
        move: {x:0,y:0,eX:0,eY:0},	//手动层缓存对象
		line: {x:0,y:0,eX:0,eY:0},	//拖动线缓存对象
		sq: {t:0,l:0,x:0,y:0,w:0,h:0,st:0}	//框选缓存对象
    },Return = {};

	//获取透明遮罩层
	var GetLayOutBox = function(){
		if(!_cache.LayOutBox){
			_cache.LayOutBox = $('<div style="z-index: 1000000003; display: none;background: none repeat scroll 0 0 black;height: 100%;left: 0;position: absolute;top: 0;width: 100%;filter:alpha(opacity=0);-moz-opacity:0;opacity:0;"><div style="height:100%;width:100%;"></div></div>');
			$(document.body).append(_cache.LayOutBox);
		}
		return _cache.LayOutBox;
	}
    
    Return.GetLayOutBox = GetLayOutBox;

	//移动层，mouseover函数
    var moveBoxFun = function(e){
        //鼠标移动
        if(_cache.move.state){			
			_cache.move.eX = e.screenX;
			_cache.move.eY = e.screenY;
			var lessX = _cache.move.eX - _cache.move.x;
			var lessY = _cache.move.eY - _cache.move.y;
			if(_cache.move.box){
				var t = _cache.move.sT + lessY;
				var l = _cache.move.sL + lessX;
				if(t > _cache.move.maxT){
					t = _cache.move.maxT;
				}
				else if(t < _cache.move.minT){
					t = _cache.move.minT;
				}
				if(l > _cache.move.maxL){
					l = _cache.move.maxL;
				}
				else if(l < _cache.move.minL){
					l = _cache.move.minL;
				}
				_cache.move.box.css({
					left: l + "px",
					top: t + "px"
				});
			}
			if(e.data.move_callback){
				e.data.move_callback();
			}
            return false;
        }
    }

	/*
		绑定移动函数
		obj
		{
			ClickBox 	--点击的标签
			Box		--移动的层
		}
	*/
    Return.MoveBox = function(obj){
        var outer = obj.Outer;
        var box = obj.Box;
		obj.ClickBox.attr("ws_property","1");
        obj.ClickBox.bind("mousedown",{box:box,outer:outer,callback:obj.Callback, move_callback: obj.MoveCallback},function(e){
            _cache.MoveLayOut = GetLayOutBox();
			_cache.MoveLayOut.css({cursor:"default"});
			var lay = ($.browser.msie)? _cache.MoveLayOut : $(window);
			lay.unbind("mousemove").bind("mousemove",{move_callback:e.data.move_callback},function(e){if(_cache.move.state){_cache.MoveLayOut.show();}moveBoxFun(e);return false;});
			lay.unbind("mouseup").bind("mouseup",function(e){
				//鼠标按起来
				if(_cache.move.state){
					_cache.move.state = false;
					_cache.MoveLayOut.hide();
					_cache.MoveLayOut.css({cursor:"default"});
					if($.browser.msie){
						_cache.MoveLayOut[0].releaseCapture();
					}
					//return false;
				}
			});
			
			if($.browser.msie){
				_cache.MoveLayOut[0].setCapture();
			}

			_cache.move.state = true;
			_cache.move.box = e.data.box;
            _cache.move.outer = e.data.outer;
			_cache.move.x = e.screenX;
			_cache.move.y = e.screenY;
			_cache.move.eX = e.screenX;
			_cache.move.eY = e.screenY;
			_cache.move.sT = _cache.move.box.offset().top;
			_cache.move.sL = _cache.move.box.offset().left;
			_cache.move.minT = _cache.move.outer.offset().top;
			_cache.move.maxT = _cache.move.outer.offset().top + _cache.move.outer.height() - _cache.move.box.height();
			_cache.move.minL = _cache.move.outer.offset().left;
			_cache.move.maxL = _cache.move.outer.offset().left + _cache.move.outer.width() - _cache.move.box.width();
			
            if(e.data.callback){
				e.data.callback();
			}

            return false;
        });
		return {
			Disable: function(){
				obj.ClickBox.attr("stop_move","1");
			},
			Enable: function(){
				obj.ClickBox.attr("stop_move")
			}
		}
    }
	
	/*
		绑定移动线
		line: 拖动的线条
		type: 拖动手势 (e-resize：箭头朝左右方向; n-resize：箭头朝上下方向; w-resize:箭头朝右上左下方向; ne-resize:箭头朝右下方向)
	*/
	Return.MoveLine = function(line,type,callback,mousedown){
		line.css({cursor:type});
		line.bind("mousedown",{type:type,callback:callback,down:mousedown},function(e){
			_cache.MoveLayOut = GetLayOutBox();
			_cache.MoveLayOut.css({cursor:e.data.type});
			var lay = ($.browser.msie)? _cache.MoveLayOut : $(window);
			//绑定事件
			lay.unbind("mousemove").bind("mousemove",{callback:e.data.callback},function(e){
				if(_cache.line.state){
					_cache.line.eX = e.screenX;
					_cache.line.eY = e.screenY;
					
					if(e.data.callback){
						e.data.callback(_cache.line);
					}
					return true;
				}
			}).unbind("mouseup").bind("mouseup",function(e){
				if(_cache.line.state){
					_cache.line.state = false;
					_cache.MoveLayOut.hide();
					if($.browser.msie){
						_cache.MoveLayOut[0].releaseCapture();
					}
					_cache.MoveLayOut.css({cursor:"default"});
					return false;
				}
			});
			_cache.MoveLayOut.show();
			if($.browser.msie){
				_cache.MoveLayOut[0].setCapture();
			}
			_cache.line.state = true;
			_cache.line.x = e.screenX;
			_cache.line.eX = e.screenX;
			_cache.line.y = e.screenY;
			_cache.line.eY = e.screenY;
			if(e.data.down){
				e.data.down();
				
			}
			
			return false;
		})
	}

	/****选择框****/
	//选择框事件对象
	var sqEvent = {
		//鼠标移动事件
		move:function(e){
			if(_cache.sq.movestate){
				var eX = e.screenX, eY = e.screenY;
				var lessX = eX - _cache.sq.sX, lessY = eY - _cache.sq.sY;
				
				var w = Math.abs(lessX);
				var h = Math.abs(lessY);
				
				var t = lessY? _cache.sq.sT : _cache.sq.sT + lessY, l = lessX? _cache.sq.sL : _cache.sq.sL + lessX;
				var oH = _cache.sq.outer.height() - 2;
				var oW = _cache.sq.dom.width() - 2;
				var scrollTop = _cache.sq.outer.scrollTop();
				var scrollLeft = _cache.sq.outer.scrollLeft();
				if(lessY < 0){
					t = t - h;
				}
				if(lessX < 0){
					l = l - w;
				}
				
				if(t < 0){
					h += t;
					t = 0;
				}
				else if(t > 0 && (t - scrollTop + h) > oH){
					h = oH - t + scrollTop;
				}
				
				if(l < 0){
					w += l;
					l = 0;
				}
				else if(l > 0 && (l - scrollLeft + w) > oW){
					w = oW - l + scrollLeft;
				}
				_cache.sq.box.height(h).css({width: w + "px", left: l + "px", top: t + "px"});
				
				if(_cache.events.mousemove){
					var l = _cache.sq.box.offset().left, t = _cache.sq.box.offset().top, w = _cache.sq.box.width(), h = _cache.sq.box.height();
					_cache.events.mousemove(l, t, l+w, t+h, e.ctrlKey, e);
				}
				if(!$.browser.msie){
					_cache.sq.box.show();
				}
				return true;
			}
		},
		//mouseup事件
		up: function(e){
			if(_cache.sq.movestate){
				_cache.sq.box.show();
				if(_cache.events.mouseup){
					var l = _cache.sq.box.offset().left, t = _cache.sq.box.offset().top, w = _cache.sq.box.width(), h = _cache.sq.box.height();
					_cache.events.mouseup(l, t, l+w, t+h, e.ctrlKey, e);
				}
				_cache.sq.box.hide();
				_cache.sq.movestate = false;
				_cache.sq.x = _cache.sq.y = _cache.sq.w = _cache.sq.h = _cache.sq.t = _cache.sq.l = _cache.sq.st = 0;
				if($.browser.msie){
					_cache.MoveLayOut && _cache.MoveLayOut[0].releaseCapture();
				}
				_cache.MoveLayOut && _cache.MoveLayOut.hide();
				return true;
			}
		}
	}

	/*
		拖动选择
	*/
	Return.Square = function(dom, outer, events){
		//绑定所在页事件
		dom.bind("mousedown",{outer:outer},function(e){
			
			//_cache.MoveLayOut = GetLayOutBox();
			//_cache.MoveLayOut.show();
			if($.browser.msie){
				_cache.MoveLayOut = GetLayOutBox();
				_cache.MoveLayOut.show();
				_cache.MoveLayOut[0].setCapture();
			}
			var lay = ($.browser.msie)? _cache.MoveLayOut : $(window);
			lay.unbind("mousemove").bind("mousemove",sqEvent.move).unbind("mouseup").bind("mouseup",sqEvent.up);
			
			if(!_cache.sq.box){
				_cache.sq.box = $('<div style="position:absolute; top:0; left:0; border:1px solid '+Util.CONFIG.SQBrdColor+'; background:'+Util.CONFIG.SQBgColor+'; filter:Alpha(Opacity='+Util.CONFIG.SQOpacity+'); opacity:0.'+Util.CONFIG.SQOpacity+'; overflow:hidden; display:none; z-index:99999;"></div>');
				$(document.body).append(_cache.sq.box);
				
			}
			
			var box = $(this);
			
			
			box.append(_cache.sq.box);
			_cache.sq.movestate = true;
			_cache.sq.outer = e.data.outer;
			var scrollTop = _cache.sq.outer.scrollTop();
			var scrollLeft = _cache.sq.outer.scrollLeft();
			_cache.sq.sX = e.screenX;
			_cache.sq.sY = e.screenY;
			_cache.sq.w = 0;
			_cache.sq.h = 0;
			_cache.sq.sT = e.clientY - _cache.sq.outer.offset().top + scrollTop;
			_cache.sq.sL = e.clientX - _cache.sq.outer.offset().left + scrollLeft;
			_cache.sq.dom = box;
			_cache.events = !events? {} : events;
			var defaultLen = (!$.browser.msie)? 0 : 1;
			if(box.css("position") == "absolute" || box.css("position") == "relative"){
				_cache.sq.box.width(defaultLen).height(defaultLen).css({top:_cache.sq.sT + "px", left: _cache.sq.sL + "px"});
			}
			else{
				_cache.sq.box.width(defaultLen).height(defaultLen).css({top:(_cache.sq.sT - scrollTop) + "px", left: _cache.sq.sL + "px"});
			}
			_cache.sq.box.show();
			if(_cache.events.mousedown){
				var l = _cache.sq.box.offset().left, t = _cache.sq.box.offset().top, w = _cache.sq.box.width(), h = _cache.sq.box.height();
				_cache.events.mousedown(l, t, l+w, t+h, e.ctrlKey, e);
				
			}
			if(!$.browser.msie){
				_cache.sq.box.hide();
			}
			return true;
		});
        
        try{
		if(parent){
			//绑定父框架事件
			$(parent.document).bind("mousemove", sqEvent.move).bind("mouseup", sqEvent.up);
		}
        }catch(e){}
		return {
			Disable: function(){
				if(_cache.sq.movestate){
					_cache.sq.movestate = false;
					_cache.sq.box.hide();
					_cache.sq.x = _cache.sq.y = _cache.sq.w = _cache.sq.h = _cache.sq.t = _cache.sq.l = _cache.sq.st = 0;
					if($.browser.msie){
						_cache.MoveLayOut[0].releaseCapture();
					}
					_cache.MoveLayOut.hide();
					return false;
				}
			}
		}
	}
	/****END 选择框****/

    return Return;
})();


//标签控制
Util.Layer = (function(){
	var _cache = {},Return = {};	//缓存类
	
	//最小化
    Return.Min = function(box,mBox,callback){
        if(!_cache.MinBorder){
            _cache.Minborder = $('<div style="z-index:10000;border:1px solid #333;position:absolute;top:0;left0;display:none;"></div>');
            $(document.body).append(_cache.Minborder);
        }
        mBox.show();
        var w = box.width(), h = box.height(), t = box.offset().top, l = box.offset().left, eT = mBox.offset().top, eL = mBox.offset().left, eW = mBox.width(), eH = mBox.height();
        _cache.Minborder.width(w).height(h).css({
            left:l,
            top:t
        });
        _cache.Minborder.animate({
            width:eW,
            height:eH,
            top:eT,
            left:eL
        },250,function(){
            _cache.Minborder.hide();
        });

        if(callback){
            callback();
        }
    }
	
	/*
	设置标签居中(左右居中，上下1:2)
	
	*/
	Return.Center = function(box,setting){
		var mainBox;
		var cut = 0, t = 0, l = 0;
		if(setting){
			if(setting.Main){
				mainBox = setting.Main;
				t = mainBox.offset().top;
				l = mainBox.offset().left;
			}
			else{
				mainBox = $(window);
			}
			if(setting.Cut != undefined){
				cut = setting.Cut;
			}
		}
		else{
			mainBox = $(window);
		}
		
		var cssT = (mainBox.height() - box.height())/3 + cut + t;
		var cssL = (mainBox.width() - box.width())/2 + cut + l;
		if(cssT < 0){
			cssT = 0;
		}
		if(cssL < 0){
			cssL = 0;
		}
		
		box.css({
			top: cssT, 
			left: cssL
		});
	}
		
	return Return;
})();
